<template>
	<view class="s-datetime-picker">
		<!-- 遮罩层 -->
		<view :class="['popup-mask',  showPicker?'show':'']" @tap="cancel"></view>
		<!-- 内容 -->
		<view :class="['popup-content',  showPicker?'show':'']">
			<!-- 顶部 -->
			<view class="popup-content-head" @touchmove.stop.prevent catchtouchmove="true">
				<view class="item-btn" @tap="cancel">取消</view>
				<view class="range-text">
					<text :style="{ color: diffTime == '请选择正确的时间' ? 'red' : '#1f2334' }">{{ diffTime }}</text>
				</view>
				<view class="item-btn confirm-btn" @tap="handleConfirm">确定</view>
			</view>
			<!-- tab栏 -->
			<view class="picker-tab-block">
				<view @click="open('start')" :class="['picker-select-item', openType=='start'?'is-actived':'']">
					取车时间
					<view class="date">
						{{ start | dateFilter }}
					</view>
				</view>
				<view @click="open('end')" :class="['picker-select-item', openType=='end'?'is-actived':'']">
					还车时间
					<view class="date">
						{{ end | dateFilter }}
					</view>
				</view>
			</view>
			<!-- 时间选择器 -->
			<view class="picker-view-block">
				<picker-view v-if="showPicker" :value="openType=='start'?startCurrent:endCurrent" @change="onDateTimeChange" class="picker-view" indicator-style="height: 44px;">
					<!-- 月份 周几 -->
					<picker-view-column v-if="openType=='start'">
						<view class="select-item" v-for="(item,index) in startDayList" :key="index">{{ item | pickerViewDateFilter }}</view>
					</picker-view-column>
					<!-- 月份 周几 -->
					<picker-view-column v-if="openType=='end'">
						<view class="select-item" v-for="(item,index) in endDayList" :key="index">{{ item | pickerViewDateFilter }}</view>
					</picker-view-column>
					<!-- 时 -->
					<picker-view-column>
						<view class="select-item" v-for="(item,index) in hourList" :key="index">{{item}}时</view>
					</picker-view-column>
					<!-- 分 -->
					<picker-view-column>
						<view class="select-item" v-for="(item,index) in minuteList" :key="index">{{item}}分</view>
					</picker-view-column>
				</picker-view>
			</view>
		</view>
	</view>
</template>

<script>
	import dayjs from 'dayjs';
	export default {
		name: "times-picker",
		data() {
			return {
				showPicker: false,
				openType: 'start',
				
				startDayList: [], // 开始 天列表
				endDayList: [], // 结束 天列表
				hourList: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14',
					'15', '16', '17', '18', '19', '20', '21', '22', '23'
				], // 时列表
				minuteList: ['00', '10', '20', '30', '40', '50'], // 分钟列表 

				startCurrent: [], //开始日期时间对应的下标
				endCurrent: [], //结束日期时间对应的下标

				start: '', // 开始日期 如“2022-12-01 13:20:00”
				end: '', // 结束日期
				minDiffDay: 1, // 最短起租时长 （首页默认租期））
			};
		},
		computed: {
			diffTime() {
				let start = this.start
				let end = this.end
				if (start && end) {
					var startTime = new Date(start.replace(/-/g, "/")); // 开始时间
					var endTime = new Date(end.replace(/-/g, "/")); // 结束时间
					var usedTime = endTime - startTime; // 相差的毫秒数
					var days = Math.floor(usedTime / (24 * 3600 * 1000)); // 计算出天数
					var leavel = usedTime % (24 * 3600 * 1000); // 计算天数后剩余的时间
					var hours = Math.floor(leavel / (3600 * 1000)); // 计算剩余的小时数
					var leavel2 = leavel % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
					var minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
					if (days > 0 || hours > 0 || minutes > 0) {
						return (
							(days > 0 ? days + "天" : "") +
							(hours > 0 ? hours + "时" : "") +
							(minutes > 0 ? minutes + "分" : "")
						);
					} else {
						return '请选择正确的时间'
					}
				} else {
					return "";
				}
			}
		},
		filters: {
			dateFilter(val) {
				var dayjsVal = dayjs(val)
				var week = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
				var weekStr = week[dayjsVal.day()]
				return `${dayjsVal.format('MM月DD日')} ${weekStr} ${dayjsVal.format('HH:mm')}`
			},
			pickerViewDateFilter(val) {
				var dayjsVal = dayjs(val)
				var week = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
				var weekStr = week[dayjsVal.day()]
				return `${dayjsVal.format('MM月DD日')} ${weekStr}`
			}
		},
		methods: {
			// 初始化
			init(startTime, endTime) {
				this.start = startTime
				this.end = endTime
				// start 和 end 的 dayjs 实例
				var dayjsStart = dayjs(this.start)
				var dayjsEnd = dayjs(this.end)
				// 对比开始时间和当前时间，获取较小的那个
				var dayjsNow = dayjs()
				if (dayjsNow.isBefore(dayjsStart)) {
					dayjsStart = dayjs()
				}
				/**
				 * 计算 dayList
				 * 开始时间可选范围，dayjsStart + 60
				 * 结束时间可选范围，dayjsStart + 60 + 15
				 */
				var startMaxOptionDay = 60;
				var startBegin = dayjsStart.format('YYYY-MM-DD')
				var startEnd = dayjsStart.add(startMaxOptionDay, 'days').format('YYYY-MM-DD')
				this.startDayList = this.formatEveryDay(startBegin, startEnd); //开始日期组

				var endMaxOptionDay = 60 + 15;
				var endBegin = dayjsStart.format('YYYY-MM-DD')
				var endEnd = dayjsStart.add(endMaxOptionDay, 'days').format('YYYY-MM-DD')
				this.endDayList = this.formatEveryDay(endBegin, endEnd); //结束日期组
				// 计算日期列
				this.startCurrent[0] = 0;
				this.endCurrent[0] = 1;
				this.startDayList.forEach((item, index) => {
					if (dayjs(item).unix() == dayjs(this.start).startOf('day').unix()) {
						this.startCurrent[0] = index;
					}
				})
				this.endDayList.forEach((item, index) => {
					if (dayjs(item).unix() == dayjs(this.end).startOf('day').unix()) {
						this.endCurrent[0] = index;
					}
				})

				// 此处计算列位置 start 使用 this.start
				const tempStart = dayjs(this.start)
				// 计算小时列
				this.hourList.forEach((item, index)=>{
					if(item == tempStart.get('h')){
						this.startCurrent[1] = index;
					}
					if(item == dayjsEnd.get('h')){
						this.endCurrent[1] = index;
					}
				})
				// 计算分钟列
				this.minuteList.forEach((item, index)=>{
					if(item == tempStart.get('minute')){
						this.startCurrent[2] = index;
					}
					if(item == dayjsEnd.get('minute')){
						this.endCurrent[2] = index;
					}
				})
			},
			// 获取开始及结束之间的时间集合（格式：xx年xx月xx日 周x）
			formatEveryDay(start, end) {
				let dateList = [];
				var startTime = new Date(dayjs(start).format('YYYY-MM-DD'));
				var endTime = new Date(dayjs(end).format('YYYY-MM-DD'));

				while ((endTime.getTime() - startTime.getTime()) >= 0) {
					var year = startTime.getFullYear();
					var month = startTime.getMonth() + 1;
					var date = startTime.getDate();
					dateList.push(year + "-" + month + "-" + date);

					startTime.setDate(startTime.getDate() + 1);
				}
				return dateList;
			},
			/**
			 * 日期时间发生变化
			 */
			onDateTimeChange(e) {
				const selectVal = e.detail.value
				// 默认开始时间(取车时间)
				var start = this.start;
				// 默认结束时间(还车时间)
				if(this.openType == 'start'){
					this.startCurrent = selectVal;
					this.endCurrent = [this.startCurrent[0] + this.minDiffDay, this. startCurrent[1], this.startCurrent[2]]

					this.updateDate('start')
					this.updateDate('end')
				}
				if(this.openType == 'end'){
					this.endCurrent = selectVal;

					this.updateDate('end')
				}
			},
			/**
			 * 根据 current 更新 date
			 */
			updateDate(type) {
				let current, dayList;
				if (type == 'start') {
					current = this.startCurrent
					dayList = this.startDayList
				}
				if (type == 'end') {
					current = this.endCurrent
					dayList = this.endDayList
				}

				let current$0 = current[0]
				let current$1 = current[1]
				let current$2 = current[2]

				let day = dayList[current$0]
				let hour = this.hourList[current$1]
				let minute = this.minuteList[current$2]

				const dateTimeStr = `${day} ${hour}:${minute}`
				
				type == 'start' ? this.start = dateTimeStr : this.end = dateTimeStr
			},
			// 打开
			open(type, defaultDays) {
				this.openType = type;
				this.showPicker = true;
			},
			// 关闭
			close() {
				this.showPicker = false;
			},
			// 取消
			cancel() {
				this.close();
			},
			// 确定
			handleConfirm() {
				// 如果开始时间比当前时间早
				let start = this.start
				// if (dayjs(start).isBefore(dayjs())) {
				// 	this.$u.toast('取车时间已经过期')
				// 	return false
				// }
				if (this.diffTime == '请选择正确的时间') {
					this.$u.toast('用车时间最少10分钟')
					return false
				}
				this.$emit('confirm', this.start, this.end);
				// 关闭弹框
				this.close();
			},
		}
	}
</script>

<style lang="scss" scoped>
	.popup-mask {
		position: fixed;
		z-index: 1000;
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.4);
		visibility: hidden;
		opacity: 0;
		transition: all 0.3s ease;

		&.show {
			visibility: visible;
			opacity: 1;
		}
	}

	.popup-content {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		transition: all 0.3s ease;
		transform: translateY(100%);
		z-index: 99999;
		background-color: #ffffff;
		// 安全底部距离
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		&.show {
			transform: translateY(0);
		}

		&-head {
			width: 100%;
			height: 120rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 2px solid #f1f2f5;
			color: #1f2334;

			.item-btn {
				font-size: 32rpx;
				font-weight: 400;
				line-height: 44rpx;
				padding: 28rpx;
			}

			.range-text {
				font-size: 28rpx;
				font-weight: 700;
				line-height: 40rpx;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
			}
			.default-tips{
				font-weight: 300;
				color: #2F86F6;
				font-size: 24rpx;
			}

			.confirm-btn {
				color: #2f86f6;
				font-weight: 700;
			}
		}

		.picker-tab-block {
			display: flex;

			.picker-select-item {
				padding: 12rpx 0;
				flex: 1;
				background-color: #f3f6fb;
				color: #000000;
				text-align: center;
				font-size: 22rpx;
				font-weight: 400;
				line-height: 32rpx;

				.date {
					margin-top: 2rpx;
					font-size: 26rpx;
					line-height: 36rpx;
				}

				&.is-actived {
					background-color: #282e44;
					color: #ffffff;
				}
			}
		}

		.picker-view-block {
			height: 446rpx;
		}

		.picker-view {
			height: 100%;
			box-sizing: border-box;

			.select-item {
				text-align: center;
				width: 100%;
				height: 44px;
				line-height: 44px;
				text-overflow: ellipsis;
				white-space: nowrap;
				font-size: 30rpx;
			}
		}
	}
</style>
